package com.example.blogdemo1.service;

/*
 * @author zzr
 * @date: 2025/10/05  21:09
 * @description:
 */

import com.example.blogdemo1.common.constants.Constants;
import com.example.blogdemo1.common.exception.BolgException;
import com.example.blogdemo1.common.model.BlogInfo;
import com.example.blogdemo1.common.model.Result;
import com.example.blogdemo1.common.model.UserInfo;
import com.example.blogdemo1.common.utils.JWTUtils;
import com.example.blogdemo1.common.utils.SecurityUtils;
import com.example.blogdemo1.mapper.BlogMapper;
import com.example.blogdemo1.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BlogMapper blogMapper;
    public Result login(String username, String password) {

        // 验证账号密码是否正确
        UserInfo userInfo = userMapper.selectByName(username);
        if (userInfo == null || userInfo.getId() == null) {
            log.error("用户不存在");
            return Result.fail("用户不存在");
        }


        if (!SecurityUtils.verify(password, userInfo.getPassword())){
            System.out.println(password);
            System.out.println(userInfo.getPassword());
            log.error("密码错误");
            return Result.fail("密码错误");
        }

        // 密码正确，返回 token
        Map<String, Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_ID,userInfo.getId());
        claim.put(Constants.TOKEN_USERNAME,userInfo.getUserName());

        String token = JWTUtils.genJwtToken(claim);
        log.info("USerController#login 返回结果 token：{}", token);
        return Result.succcess(token);

    }

    public UserInfo getUserInfo(HttpServletRequest request) {
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        // 从 token 中获取用户 ID
        Integer userId = JWTUtils.getIdByToken(token);
        if (userId == null) {
            return null;
        }
        UserInfo userInfo = userMapper.selectById(userId);
        return userInfo;
    }

    public UserInfo selectAuthorInfoByBlogId(Integer blogId) {

        // 根据博客id 获得博客信息 ==》 博客信息中包含作者id
        BlogInfo blogInfo = blogMapper.selectById(blogId);
        // 根据作者 id 获得作者信息
        if (blogInfo == null) {
            log.error("博客不存在");
        }
        UserInfo userInfo = userMapper.selectById(blogInfo.getUserId());

        return userInfo;
    }
}
